package com.atguigu.gmall.order.receiver;

import com.alibaba.fastjson.JSON;
import com.atguigu.gmall.common.constant.MqConst;
import com.atguigu.gmall.model.enums.ProcessStatus;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.model.payment.PaymentInfo;
import com.atguigu.gmall.order.service.OrderService;
import com.atguigu.gmall.payment.client.PaymentFeignClient;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Map;

@Component
public class OrderReceiver {
    @Autowired
    private OrderService orderService;
    @Autowired
    private PaymentFeignClient paymentFeignClient;

    //订单过期，消息队列监听器
    @SneakyThrows
    @RabbitListener(queues = MqConst.QUEUE_ORDER_CANCEL)
    public void orderCancel(Long orderId, Message message, Channel channel){
        try {
            if (orderId != null){
                OrderInfo orderInfo = orderService.getById(orderId);
                //若还是未支付状态，则改为关闭订单状态
                if (orderInfo !=null && "UNPAID".equals(orderInfo.getProcessStatus())
                        && "UNPAID".equals(orderInfo.getOrderStatus())){
                    PaymentInfo paymentInfo = paymentFeignClient.getPaymentInfo(orderInfo.getOutTradeNo());
                    //有疑问，若paymentInfo不为空，且是已支付状态，怎么办？
                    //if (paymentInfo != null && "UNPAID".equals(paymentInfo.getPaymentStatus())){
                    if (paymentInfo != null){
                        Boolean aBoolean = paymentFeignClient.checkPay(orderId);
                        if (aBoolean){
                            Boolean flag = paymentFeignClient.closePay(orderId);
                            if (flag){
                                //关闭支付宝交易成功，表明，用户刚扫完码，还未支付，则关闭订单及支付信息
                                orderService.execExpiredOrder(orderId,"2");
                            }else {
                                //关闭支付宝交易失败，表明已经支付完成，则不需要再关闭订单和支付信息状态了
                            }
                        }else {
                            //支付宝没有交易信息，则二维码还未扫描，未支付，关闭订单，及支付信息状态
                            orderService.execExpiredOrder(orderId,"2");
                        }

                    }else {
                        //支付信息为空，则只关闭订单状态
                        orderService.execExpiredOrder(orderId,"1");
                    }

                }
            }
        } catch (Exception e) {
            //e.printStackTrace();
            //  消息没有正常被消费者处理：
            //  第一个参数就是long 标识， 第二个参数表示 是否批量确认 ，第三个参数是否重回队列
            channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);
            //  发短信的形式通知我们的管理员，立刻查看并解决问题 类似于消息的积压！
            //  如果线上真的出现了这种问题，你能停止这个微服务改代码? 跟我刚刚的操作类似，启动一个其他的程序消费这个消息！
        }
        //  手动确认消息 如果不确认，有可能会到消息残留。
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }

    //支付成功后，更新了支付状态，还需更新订单状态，监听队列，接收消息
    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_PAYMENT_PAY,durable = "true",autoDelete = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_PAYMENT_PAY),
            key = {MqConst.ROUTING_PAYMENT_PAY}
    ))
    public void paymentPay(Long orderId,Message message,Channel channel){
        if (orderId != null){
            OrderInfo orderInfo = orderService.getOrderInfoById(orderId);
            if (orderInfo != null && "UNPAID".equals(orderInfo.getOrderStatus()) && "UNPAID".equals(orderInfo.getProcessStatus())){
                //更新订单状态为已支付状态
                orderService.updateOrderStatus(orderId, ProcessStatus.PAID);
                //减库存（封装方法）
                orderService.sendOrderStatus(orderId);
            }
        }
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }

    //库存系统完成减库存后，会发送MQ消息，消息为 Map，中有orderId 和 status（减库存是否成功【状态】）
    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_WARE_ORDER,durable = "true",autoDelete = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_WARE_ORDER),
            key = {MqConst.ROUTING_WARE_ORDER}
    ))
    public void updateOrderStatus(String wareJson,Message message,Channel channel){
        if (!StringUtils.isEmpty(wareJson)){
            Map map = JSON.parseObject(wareJson, Map.class);
            String orderId = (String) map.get("orderId");
            String status = (String) map.get("status");

            //DEDUCTED 说明减库存成功
            if ("DEDUCTED".equals(status)){
                //更新订单状态为待发货状态
                orderService.updateOrderStatus(Long.parseLong(orderId),ProcessStatus.WAITING_DELEVER);
            }else {
                orderService.updateOrderStatus(Long.parseLong(orderId),ProcessStatus.STOCK_EXCEPTION);
            }
        }
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);//false代表,不批量处理消息
    }

}
